﻿using System;
using System.Linq;
using db = DataContext;

namespace WebApplication.admin
{
	public partial class ProductTypes : System.Web.UI.Page
	{
		public int id;

		protected void Page_Load(object sender, EventArgs e)
		{
			Common.CheckLogin();

			id = Common.Id;
			db.ProductType type;

			using (db.DbDataContext context = new db.DbDataContext())
			{
				t_list.DataSource = context.ProductType;
				t_list.DataBind();

				if (Common.IsEdit)
				{
					type = context.ProductType.Single(x => x.Id == id);
					name.Value = type.Name;
					sort.Value = type.Sort.ToString();

					parent.DataSource = context.ProductType.Where(x => x.Id != id);
					parent.DataBind();
					parent.Items.Insert(0, new System.Web.UI.WebControls.ListItem("顶层分类...", "0"));
					if (type.ParentId.HasValue) parent.Value = (type.ParentId ?? 0).ToString();
				} else
				{
					parent.DataSource = context.ProductType;
					parent.DataBind();
					parent.Items.Insert(0, new System.Web.UI.WebControls.ListItem("顶层分类...", "0"));
				}

				if (Common.IsSave)
				{
					int parentid = int.Parse("0" + Request.Form["parent"]);
					if (id > 0)
					{
						type = context.ProductType.Single(x => x.Id == id);
						type.Name = Request.Form["name"];
						type.Sort = int.Parse(Request.Form["sort"]);
						type.ParentType = context.ProductType.SingleOrDefault(x => x.Id == parentid);
						context.SubmitChanges();
					} else
					{
						context.ProductType.InsertOnSubmit(new db.ProductType
						{
							Name = Request.Form["name"],
							Sort = int.Parse(Request.Form["sort"]),
							ParentType = context.ProductType.SingleOrDefault(x => x.Id == parentid)
						});
						context.SubmitChanges();
					}
					Response.Redirect("product_types.aspx", true);
				}

				if (Common.IsDelete)
				{
					type = context.ProductType.Single(x => x.Id == id);
					if (type.Product.Count > 0)
					{
						msg.InnerText = "类别【"+type.Name+"】中还有产品，不能删除该分类。";
					} else
					{
						context.ProductType.DeleteOnSubmit(type);
						context.SubmitChanges();
						Response.Redirect("product_types.aspx", true);
					}
				}
			}
		}
	}
}